const fs = require('fs')
const path = require('path')
const root = path.join(__dirname, '../survey-data/answers-raw-data')

function initNewAnswer(survey_id) {
    fs.mkdirSync(path.join(root, survey_id))
    const manage = { dump: [] }
    fs.writeFileSync(
        path.join(root, `${survey_id}/manage.json`),
        JSON.stringify(manage)
    )
}

function getSpecifyAnswerManage(survey_id) {
    const manage_path = path.join(root, `${survey_id}/manage.json`)
    return JSON.parse(fs.readFileSync(manage_path, 'utf8'))
}

function setSpecifyAnswerManage(survey_id, new_manage) {
    const manage_path = path.join(root, `${survey_id}/manage.json`)
    fs.writeFileSync(manage_path, JSON.stringify(new_manage))
}

// 计算所有问卷收集的答案数量
function countAllAnswerNum() {
    const num_arr = {}
    const all_survey_answer = fs.readdirSync(root)
    all_survey_answer.forEach(survey_id => {
        const files = fs.readdirSync(path.join(root, survey_id))
        const exclude_num = 1 + getSpecifyAnswerManage(survey_id).dump.length
        num_arr[survey_id] = files.length - exclude_num
    })
    return num_arr
}

function countSpecifyAnswerNum(survey_id) {
    const files = fs.readdirSync(path.join(root, survey_id))
    const exclude_num = 1 + getSpecifyAnswerManage(survey_id).dump.length
    return files.length - exclude_num
}

function getSpecifyAnswerId(survey_id) {
    const files = fs.readdirSync(path.join(root, survey_id))
    return files.length
}

function addAnswer(oneAnswer) {
    fs.writeFileSync(
        path.join(root, `${oneAnswer.survey_id}/${oneAnswer.id}.answer.json`),
        JSON.stringify(oneAnswer)
    )
}

function replaceAnswer(specifyAnswer) {
    fs.writeFileSync(
        path.join(
            root,
            `${specifyAnswer.survey_id}/${specifyAnswer.id}.answer.json`
        ),
        JSON.stringify(specifyAnswer)
    )
}

function delAnswer(survey_id, answer_id) {
    const manage = getSpecifyAnswerManage(survey_id)
    manage.dump.push(`${answer_id}.answer.json`)
    setSpecifyAnswerManage(survey_id, manage)
}

function getAnswers(survey_id) {
    const dirs = fs.readdirSync(path.join(root, survey_id))
    dirs.sort((a, b) => Number.parseInt(a) - Number.parseInt(b))
    const dump = getSpecifyAnswerManage(survey_id).dump
    const answers = []
    dirs.forEach(answer => {
        if (dump.includes(answer)) return
        if (answer === 'manage.json') return
        answers.push(
            JSON.parse(
                fs.readFileSync(
                    path.join(root, `${survey_id}/${answer}`),
                    'utf8'
                )
            )
        )
    })
    return answers
}

module.exports = {
    initNewAnswer,
    countAllAnswerNum,
    countSpecifyAnswerNum,
    getSpecifyAnswerId,
    addAnswer,
    replaceAnswer,
    delAnswer,
    getAnswers,
}
